package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import ysq.xyg.model.*;
import ysq.xyg.model.info.BaseUserInfo;
import ysq.xyg.model.info.Page;
import ysq.xyg.model.info.ReturnEntity;
import ysq.xyg.model.info.ReturnInfo;
import ysq.xyg.service.*;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.BaseUtil;
import ysq.xyg.util.DateUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/2/20 0020.
 */
@Controller
@RequestMapping("/baseUser")
public class BaseUserController extends BaseController {
    private static Logger log= LoggerFactory.getLogger(BaseUserController.class);
    @Resource
    private BaseUserService baseUserService;
    @Resource
    private BaseDepartService baseDepartService;
    @Resource
    private BaseMenuService baseMenuService;
    @Resource
    private StoreService storeService;
    @Resource
    private UseDoService useDoService;
    @Resource
    private BaseDepartMenuService baseDepartMenuService;
    private BaseUser baseUser;
    //登录
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public @ResponseBody
    ReturnEntity login(HttpServletRequest request, HttpServletResponse response, BaseUserInfo baseUserInfo){
        BaseUser baseUser=baseUserService.selectByPrimaryKey(baseUserInfo.getUserid());
        if(baseUser == null || "".equals(baseUser)){
            return new ReturnEntity(BaseConstant.CODE_ERROR,BaseConstant.LOGIN_ERROR_NOID);
        }
        if(BaseConstant.REMOVE_Y.equalsIgnoreCase(baseUser.getRemovetag())){
            return new ReturnEntity(BaseConstant.CODE_ERROR,BaseConstant.LOGIN_ERROR_NOID);
        }
        if(!(baseUserInfo.getUserpassword().equals(baseUser.getUserpassword()))){
            return new ReturnEntity(BaseConstant.CODE_ERROR,BaseConstant.LOGIN_ERROR_PSW);
        }
        if(baseUserInfo.getAutoLogin() == BaseConstant.CODE_AUTOLOGIN_Y){
            BaseController.CookiesAddObject(request,response,BaseConstant.COOKIE_LOGINNAME,baseUserInfo.getUserid());
            BaseController.CookiesAddObject(request,response,BaseConstant.COOKIE_PASSWORD,baseUserInfo.getUserpassword());
        }else{
            BaseController.CookiesDeleteObject(request,response,BaseConstant.COOKIE_LOGINNAME);
            BaseController.CookiesDeleteObject(request,response,BaseConstant.COOKIE_PASSWORD);
        }
        BaseDepart baseDepart=baseDepartService.selectByPrimaryKey(baseUser.getDepartid());
        baseUserInfo.setDepartid(baseUser.getDepartid());
        baseUserInfo.setUsername(baseUser.getUsername());
        baseUserInfo.setUserpassword(baseUser.getUserpassword());
        baseUserInfo.setBaseDepart(baseDepart);
        baseUserInfo.setHeadLogo(baseUser.getHeadlogo());
        request.getSession().setAttribute(BaseConstant.SESSION_USERINFO,baseUserInfo);
        useDoService.insert(new UseDo(baseUserInfo.getUserid(),"登录系统",BaseConstant.USE_DO_TYPE_LOGIN));
        return new ReturnEntity(BaseConstant.CODE_SUCCESS,baseUserInfo,"index");
    }
    //退出
    @RequestMapping(value="/Exit",method= RequestMethod.GET)
    public String selectUser(HttpServletRequest request,Model model){
        BaseUserInfo baseUserInfo=acceptCurrentUser(request);
        BaseController.SessionDeleteObject(request,BaseConstant.SESSION_USERINFO);
        useDoService.insert(new UseDo(baseUserInfo.getUserid(),"退出系统",BaseConstant.USE_DO_TYPE_EXIT));
        return "redirect:/";
    }


    //图片上传
    @RequestMapping(value="/upload")
    public String showUploadPage(){
        return "user_admin/file";
    }

    @RequestMapping(value="/doUpload",method=RequestMethod.POST)
    public String doUploadFile(@RequestParam("file")MultipartFile file) throws IOException{
        if (!file.isEmpty()) {
            log.info("Process file:{}",file.getOriginalFilename());
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\",System.currentTimeMillis()+file.getOriginalFilename()));
        return "succes";
    }

    //用户查询
    @RequestMapping("/listPage")
    public ModelAndView List(HttpServletRequest request, HttpServletResponse response,String menuid){
        return new ModelAndView("/baseUserList").addObject("headTitle",acceptTitle(menuid,baseMenuService));
    }
    //用户集合
    @RequestMapping(value = "/JsonList",method = RequestMethod.POST)
    public @ResponseBody
    JSONObject JsonList(BaseUser baseUser, Page page) throws MalformedURLException, UnsupportedEncodingException {
        baseUser.setRemovetag(BaseConstant.REMOVE_N);
        PageInfo<BaseUser> pageInfo=baseUserService.pageLeft(baseUser,page.getLimit(),page.getPage());
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","");
        jsonObject.put("count",pageInfo.getTotal());
        if(pageInfo !=null && pageInfo.getList() !=null && pageInfo.getList().size() > 0){
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for(BaseUser item:pageInfo.getList()){
                row=new JSONObject();
                row.put("userid",item.getUserid());
                row.put("username",item.getUsername());
                row.put("headlogo",item.getHeadlogo());
                row.put("username",item.getUsername());
                row.put("departName",item.getDepartName());
                row.put("createtime", DateUtil.DateToStr(item.getCreatetime(),DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    //编辑和修改查询
    @RequestMapping(value = "/SelectEntity",method = RequestMethod.GET)
    public ModelAndView SelectEntity(String userId){
        ModelAndView view=new ModelAndView("/baseUserUpdateOrSave");
        if (userId != null && !"".equals(userId)){
            BaseUser baseUser=(BaseUser)baseUserService.selectByPrimaryKey(userId);
            view.addObject(baseUser);
        }else{
            view.addObject("flage","add");
        }
        //部门查询
        BaseDepart baseDepart=new BaseDepart();
        baseDepart.setRemovetag(BaseConstant.REMOVE_N);
        List<BaseDepart> baseDepartsList=baseDepartService.select(baseDepart);
        view.addObject("baseDepartsList",baseDepartsList);
        return view;
    }

    //修改或增加
    @RequestMapping(value = "/UpdateOrAddEntity",method = RequestMethod.POST)
    public @ResponseBody JSONObject UpdateOrAddEntity(BaseUserInfo baseUserInfo,String flag){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if("add".equals(flag)){
            BaseUser baseUser1=baseUserService.selectByPrimaryKey(baseUserInfo.getUserid());
            if(baseUser1 != null){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.LOGIN_USERIS_Y.replace("NAME",baseUserInfo.getUserid()));
            }else{
                baseUser=new BaseUser();
                baseUser.setUserid(baseUserInfo.getUserid());
                baseUser.setHeadlogo(baseUserInfo.getHeadLogo());
                baseUser.setUsername(baseUserInfo.getUsername());
                baseUser.setDepartid(baseUserInfo.getDepartid());
                baseUser.setUserpassword(baseUserInfo.getUserpassword());
                baseUser.setCreatetime(new Date());
                baseUser.setRemovetag(BaseConstant.REMOVE_N);
                int id=baseUserService.insert(baseUser);
                if(id <= 0){
                    returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_INSERT);
                }
            }

        }else{
            baseUser=baseUserService.selectByPrimaryKey(baseUserInfo.getUserid());
            baseUser.setUsername(baseUserInfo.getUsername());
            baseUser.setDepartid(baseUserInfo.getDepartid());
            baseUser.setHeadlogo(baseUserInfo.getHeadLogo());
            baseUser.setUserpassword(baseUserInfo.getUserpassword());
            baseUser.setCreatetime(new Date());
            int id=baseUserService.updateByPrimaryKey(baseUser);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/DeleteEntity",method = RequestMethod.GET)
    public @ResponseBody JSONObject DeleteEntity(String userId){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(StringUtil.isEmpty(userId)){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            BaseUser baseUser=baseUserService.selectByPrimaryKey(userId);
            if(baseUser == null){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_BUCHUNZAI);
            }else{
                baseUser.setRemovetag(BaseConstant.REMOVE_Y);
                int id=baseUserService.updateByPrimaryKey(baseUser);
                if(id <= 0){
                    returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_DELETE);
                }
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }


    //个人信息查询
    @RequestMapping(value = "/SelectEntityNews",method = RequestMethod.GET)
    public ModelAndView SelectEntityNews(HttpServletResponse response,HttpServletRequest request){
        ModelAndView view=new ModelAndView("/baseUserNews");
        BaseUserInfo baseUserInfo=(BaseUserInfo) request.getSession().getAttribute(BaseConstant.SESSION_USERINFO);
        BaseUser baseUser=baseUserService.selectByPrimaryKey(baseUserInfo.getUserid());
        baseUser.setBaseDepart(baseUserInfo.getBaseDepart());
        view.addObject("baseUserInfo",baseUser);
        return view;
    }
    //个人信息修改
    @RequestMapping(value = "/Update",method = RequestMethod.POST)
    public @ResponseBody JSONObject Update(BaseUserInfo baseUserInfo,HttpServletRequest request){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        baseUser=baseUserService.selectByPrimaryKey(baseUserInfo.getUserid());
        if(baseUser == null){
            returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_CANSHU);
        }else{
            baseUser.setUsername(baseUserInfo.getUsername());
            baseUser.setHeadlogo(baseUserInfo.getHeadLogo());
            baseUser.setPhone(baseUserInfo.getPhone());
            baseUser.setProvince(baseUserInfo.getProvince());
            baseUser.setCity(baseUserInfo.getCity());
            baseUser.setArea(baseUserInfo.getArea());
            baseUser.setSex(baseUserInfo.getSex());
            baseUser.setBrithday(baseUserInfo.getBrithday());
            baseUser.setEmail(baseUserInfo.getEmail());
            baseUser.setCreatetime(new Date());
            int id=baseUserService.updateByPrimaryKey(baseUser);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_UPDATE);
            }else{
                BaseUserInfo baseUserInfos=(BaseUserInfo) request.getSession().getAttribute(BaseConstant.SESSION_USERINFO);
                baseUserInfos.setUserpassword(baseUser.getUserpassword());
                baseUserInfos.setUsername(baseUser.getUsername());
                baseUserInfos.setHeadLogo(baseUser.getHeadlogo());
                baseUserInfos.setPhone(baseUser.getPhone());
                baseUserInfos.setProvince(baseUser.getProvince());
                baseUserInfos.setCity(baseUser.getCity());
                baseUserInfos.setArea(baseUser.getArea());
                baseUserInfos.setSex(baseUser.getSex());
                baseUserInfos.setBrithday(baseUser.getBrithday());
                baseUserInfos.setEmail(baseUser.getEmail());
                request.getSession().setAttribute(BaseConstant.SESSION_USERINFO,baseUserInfos);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }


}